package jnpf.engine.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.ImmutableList;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.emnus.TemplateEnum;
import jnpf.engine.entity.*;
import jnpf.engine.enums.FlowEventEnum;
import jnpf.engine.enums.FlowMessageEnum;
import jnpf.engine.enums.FlowTaskStatusEnum;
import jnpf.engine.model.FlowTaskDTO;
import jnpf.engine.model.FlowTaskNodeDTO;
import jnpf.engine.model.FlowTaskOperatorRecordDTO;
import jnpf.engine.model.InterfaceInfoModel;
import jnpf.engine.model.flowbefore.FlowTemplateAllModel;
import jnpf.engine.model.flowdelegate.FlowDelegateModel;
import jnpf.engine.model.flowengine.FlowModel;
import jnpf.engine.model.flowengine.shuntjson.childnode.Properties;
import jnpf.engine.model.flowengine.shuntjson.childnode.*;
import jnpf.engine.model.flowmessage.FlowEventModel;
import jnpf.engine.model.flowmessage.FlowMessageModel;
import jnpf.engine.model.flowmessage.FlowMsgModel;
import jnpf.engine.model.flowtask.FlowContModel;
import jnpf.engine.service.*;
import jnpf.exception.WorkFlowException;
import jnpf.message.model.SentMessageForm;
import jnpf.permission.entity.UserEntity;
import jnpf.util.JsonUtil;
import jnpf.util.ServiceAllUtil;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.HistoryService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static jnpf.engine.custom.constants.GlobalProcessVariableConstants.*;
import static jnpf.engine.util.BpmnModelUtils.getIsStartEvent;

/**
 * @author ：JNPF开发平台组
 * @version: V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date ：2022/3/30 11:45
 */
@Slf4j
@Component
@SuppressWarnings("all")
public class FlowMsgUtil {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private FlowTaskService flowTaskService;
    @Autowired
    private ServiceAllUtil serviceUtil;
    @Autowired
    private FlowTaskUtil flowTaskUtil;
    @Autowired
    private FlowTaskNodeService flowTaskNodeService;
    @Autowired
    private FlowDelegateService flowDelegateService;
    @Autowired
    private FlowEventLogService flowEventLogService;
    @Resource
    private HistoryService historyService;

    @Resource
    private FlowTemplateJsonService flowTemplateJsonService;

    /**
     * 发送消息
     *
     * @param flowMsgModel
     */
    public void message(FlowMsgModel flowMsgModel) throws WorkFlowException {
        List<SentMessageForm> messageListAll = new ArrayList<>();
        FlowTaskDTO taskEntity  = flowMsgModel.getTaskEntity();
        List<String> creatorUserId = new ArrayList<>();
        UserEntity user = taskEntity != null ? serviceUtil.getUserInfo(taskEntity.getCreatorUserId()) : null;
        if (taskEntity != null) {
            creatorUserId.add(taskEntity.getCreatorUserId());
        }
        FlowTaskNodeDTO flowTaskNode= flowMsgModel.getTaskNodeEntity();
        FlowTemplateAllModel flowTemplateAllModel = flowMsgModel.getFlowTemplateAllModel();
        List<FlowTaskOperatorEntity> operatorList = flowMsgModel.getOperatorList();
        List<FlowTaskCirculateEntity> circulateList = flowMsgModel.getCirculateList();
        FlowModel flowModel = flowMsgModel.getFlowModel();
        UserInfo userInfo = flowModel.getUserInfo();
        FlowTaskOperatorRecordEntity recordEntity = new FlowTaskOperatorRecordEntity();
        recordEntity.setTaskId(flowMsgModel.getTaskId());
        recordEntity.setHandleId(userInfo != null ? userInfo.getUserId() : "");
        Properties currentNodeProperties = flowMsgModel.getCurrentNodeProperties();
        //等待
        if (flowMsgModel.getWait()) {

            if (currentNodeProperties.getWaitMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }

            MsgConfig taskMsgConfig = currentNodeProperties.getWaitMsgConfig();
            if (taskMsgConfig.getOn() == 3) {
                taskMsgConfig.setMsgId("PZXTLC001");
            }
            Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
            for (String key : operatorMap.keySet()) {
                recordEntity.setTaskNodeId(key);
                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
                FlowMessageModel messageModel = new FlowMessageModel();
//                FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(recordEntity.getTaskNodeId())).findFirst().orElse(null);
//                Map<String, Object> data = flowTaskUtil.infoData(taskNode.getFormId(), taskNode.getTaskId());
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setMsgConfig(taskMsgConfig);
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setFullName(taskEntity.getFullName());
//                if (StringUtil.isNotEmpty(flowMsgModel.getTitle())) {
//                    messageModel.setFullName(taskEntity.getFullName() + flowMsgModel.getTitle());
//                }
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
//                for (FlowTaskOperatorEntity operator : taskOperatorList) {
//                    List<SentMessageForm> delegationMsg = this.delegationMsg(operator, messageModel, flowTemplateAllModel);
//                    messageListAll.addAll(delegationMsg);
//                }
            }
        }
        //结束
        if (flowMsgModel.getEnd()) {
            //发起人

            if (currentNodeProperties.getEndMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getEndMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC010");
            }
            List<SentMessageForm> messageList = new ArrayList<>();
            FlowMessageModel messageModel = new FlowMessageModel();
//            String formId = properties.getFormId();
//            Map<String, Object> data = flowTaskUtil.infoData(formId, childNode.getTaskId());
            Map<String, Object> data = flowMsgModel.getData();
            messageModel.setData(data);
            messageModel.setTitle("已【结束】");
            messageModel.setMsgConfig(msgConfig);
            messageModel.setType(FlowMessageEnum.me.getCode());
            messageModel.setRecordEntity(recordEntity);
            messageModel.setStatus(taskEntity.getStatus());
            messageModel.setFullName(taskEntity.getFullName());
            messageModel.setUserInfo(userInfo);
            List<FlowTaskOperatorEntity> taskOperatorList = new ArrayList() {{
                FlowTaskOperatorEntity operatorEntity = new FlowTaskOperatorEntity();
                operatorEntity.setTaskId(flowMsgModel.getTaskId());
                operatorEntity.setTaskNodeId(flowMsgModel.getTaskNodeId());
                operatorEntity.setHandleId(taskEntity.getCreatorUserId());
                add(operatorEntity);
            }};
            this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
            this.setMessageList(messageList, messageModel);
            messageListAll.addAll(messageList);
        }
        //同意
        if (flowMsgModel.getApprove()) {
//            ChildNodeList childNode = JsonUtil.getJsonToBean(nodeJson, ChildNodeList.class);
//            Properties properties = childNode.getProperties();
//            MsgConfig msgConfig = properties.getApproveMsgConfig();
//            if (msgConfig.getOn() == 3) {
//                msgConfig.setMsgId("PZXTLC002");
//            }
//            Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
//            for (String key : operatorMap.keySet()) {
//                recordEntity.setTaskNodeId(flowTaskNode.getId());
//                //默认获取当前节点
//                FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(recordEntity.getTaskNodeId())).findFirst().orElse(null);
//                ChildNodeList taskChildNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
//                Properties taskProperties = taskChildNode.getProperties();
//                MsgConfig taskMsgConfig = taskProperties.getApproveMsgConfig();
//                if (taskMsgConfig.getOn() == 2) {
//                    taskMsgConfig = msgConfig;
//                }
//                if (taskMsgConfig.getOn() == 3) {
//                    taskMsgConfig.setMsgId("PZXTLC002");
//                }
//                List<SentMessageForm> messageList = new ArrayList<>();
//                List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
//                FlowMessageModel messageModel = new FlowMessageModel();
//                Map<String, Object> data = flowTaskUtil.infoData(taskNode.getFormId(), taskNode.getTaskId());
//                messageModel.setData(data);
//                messageModel.setTitle("已被【同意】");
//                messageModel.setMsgConfig(taskMsgConfig);
//                messageModel.setRecordEntity(recordEntity);
//                messageModel.setStatus(taskEntity.getStatus());
//                messageModel.setFullName(taskEntity.getFullName());
//                messageModel.setUserInfo(userInfo);
//                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
//                this.setMessageList(messageList, messageModel);
//                messageListAll.addAll(messageList);
//                for (FlowTaskOperatorEntity operator : taskOperatorList) {
//                    List<SentMessageForm> delegationMsg = this.delegationMsg(operator, messageModel, flowTemplateAllModel);
//                    messageListAll.addAll(delegationMsg);
//                }
//            }
        }
        //拒绝
        if (flowMsgModel.getReject()) {
            if (currentNodeProperties.getRejectMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getRejectMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC003");
            }
            Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
            for (String key : operatorMap.keySet()) {
                recordEntity.setTaskNodeId(flowMsgModel.getTaskNodeId());

                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setTitle("已被【退回】");
                messageModel.setMsgConfig(currentNodeProperties.getRejectMsgConfig());
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setType(FlowMessageEnum.me.getCode());
                messageModel.setFullName(taskEntity.getFullName());
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
//                for (FlowTaskOperatorEntity operator : taskOperatorList) {
//                    List<SentMessageForm> delegationMsg = this.delegationMsg(operator, messageModel, flowTemplateAllModel);
//                    messageListAll.addAll(delegationMsg);
//                }
            }
        }
        //抄送
        if (flowMsgModel.getCopy()) {
            if (currentNodeProperties.getCopyMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getCopyMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC007");
            }
            Map<String, List<FlowTaskCirculateEntity>> circulateMap = circulateList.stream().collect(Collectors.groupingBy(FlowTaskCirculateEntity::getTaskNodeId));
            for (String key : circulateMap.keySet()) {
                recordEntity.setTaskNodeId(key);
                //默认获取当前节点
//                FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(key)).findFirst().orElse(null);
//                ChildNodeList taskChildNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
//                Properties taskProperties = taskChildNode.getProperties();
//                MsgConfig taskMsgConfig = taskProperties.getCopyMsgConfig();
//                if (taskMsgConfig.getOn() == 2) {
//                    taskMsgConfig = msgConfig;
//                }
//                if (taskMsgConfig.getOn() == 3) {
//                    taskMsgConfig.setMsgId("PZXTLC007");
//                }
                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = new ArrayList<>();
                for (FlowTaskCirculateEntity circulateEntity : circulateMap.get(key)) {
                    FlowTaskOperatorEntity operatorEntity = JsonUtil.getJsonToBean(circulateEntity, FlowTaskOperatorEntity.class);
                    operatorEntity.setHandleId(circulateEntity.getObjectId());
                    taskOperatorList.add(operatorEntity);
                }
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setTitle("已被【抄送】");
                messageModel.setMsgConfig(currentNodeProperties.getCopyMsgConfig());
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setType(FlowMessageEnum.circulate.getCode());
                messageModel.setFullName(taskEntity.getFullName());
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
            }
        }
        //子流程
        if (flowMsgModel.getLaunch()) {
            if (currentNodeProperties.getLaunchMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getLaunchMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC011");
            }
            Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
            for (String key : operatorMap.keySet()) {
                recordEntity.setTaskNodeId(key);
                //默认获取当前节点
                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setTitle("请发起【子流程】");
                messageModel.setMsgConfig(currentNodeProperties.getLaunchMsgConfig());
                messageModel.setRecordEntity(recordEntity);
                messageModel.setType(FlowMessageEnum.me.getCode());
                messageModel.setStatus(FlowTaskStatusEnum.Draft.getCode());
                messageModel.setFullName(taskEntity.getFullName());
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
            }
        }
        //发起人
        if (flowMsgModel.getStart()) {
            if (currentNodeProperties.getRejectMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getRejectMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC003");
            }
            List<SentMessageForm> messageList = new ArrayList<>();
            FlowMessageModel meModel = new FlowMessageModel();
            Map<String, Object> data = flowMsgModel.getData();
            meModel.setData(data);
            meModel.setTitle("已被【退回】");
            meModel.setRecordEntity(recordEntity);
            meModel.setStatus(taskEntity.getStatus());
            meModel.setMsgConfig(msgConfig);
            meModel.setType(FlowMessageEnum.me.getCode());
            meModel.setFullName(taskEntity.getFullName());
            meModel.setUserInfo(userInfo);
            List<FlowTaskOperatorEntity> meOperatorList = new ArrayList() {{
                FlowTaskOperatorEntity operatorEntity = new FlowTaskOperatorEntity();
                operatorEntity.setTaskId(flowTaskNode.getTaskId());
                operatorEntity.setHandleId(taskEntity.getCreatorUserId());
                add(operatorEntity);
            }};
            this.messageModel(meOperatorList, flowTemplateAllModel, meModel);
            this.setMessageList(messageList, meModel);
            messageListAll.addAll(messageList);
        }
        //超时
        if (flowMsgModel.getOvertime()) {
            if (currentNodeProperties.getOvertimeMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getOvertimeMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC009");
            }
            Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
            for (String key : operatorMap.keySet()) {
                recordEntity.setTaskNodeId(key);
                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setTitle("已【超时】");
                messageModel.setMsgConfig(currentNodeProperties.getOvertimeMsgConfig());
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setFullName(taskEntity.getFullName());
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
//                for (FlowTaskOperatorEntity operator : taskOperatorList) {
//                    List<SentMessageForm> delegationMsg = this.delegationMsg(operator, messageModel, flowTemplateAllModel);
//                    messageListAll.addAll(delegationMsg);
//                }
            }
        }
        //提醒
        if (flowMsgModel.getNotice()) {
            if (currentNodeProperties.getNoticeMsgConfig().getOn() == 2) {
                currentNodeProperties=flowMsgModel.getStartNodeProperties();
            }
            MsgConfig msgConfig = currentNodeProperties.getNoticeMsgConfig();
            if (msgConfig.getOn() == 3) {
                msgConfig.setMsgId("PZXTLC008");
            }
            Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
            for (String key : operatorMap.keySet()) {
                recordEntity.setTaskNodeId(key);
                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setTitle("请尽快【审批】");
                messageModel.setMsgConfig(currentNodeProperties.getNoticeMsgConfig());
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setFullName(taskEntity.getFullName());
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
//                for (FlowTaskOperatorEntity operator : taskOperatorList) {
//                    List<SentMessageForm> delegationMsg = this.delegationMsg(operator, messageModel, flowTemplateAllModel);
//                    messageListAll.addAll(delegationMsg);
//                }
            }
        }

        //评论提醒
        if (flowMsgModel.getComment()) {
/*            ChildNodeList childNode = JsonUtil.getJsonToBean(nodeJson, ChildNodeList.class);
            Properties properties = childNode.getProperties();
            MsgConfig commentMsgConfig = properties.getCommentMsgConfig();
            if (commentMsgConfig.getOn() == 3) {
                commentMsgConfig.setMsgId("MBXTLC017");
            }
            //审批人
            if (operatorList != null && !operatorList.isEmpty()) {
                Map<String, List<FlowTaskOperatorEntity>> operatorMap = operatorList.stream().collect(Collectors.groupingBy(FlowTaskOperatorEntity::getTaskNodeId));
                for (String key : operatorMap.keySet()) {
                    recordEntity.setTaskNodeId(key);
                    List<SentMessageForm> messageList = new ArrayList<>();
                    List<FlowTaskOperatorEntity> taskOperatorList = operatorMap.get(key);
                    FlowMessageModel messageModel = new FlowMessageModel();
                    FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(recordEntity.getTaskNodeId())).findFirst().orElse(null);
                    Map<String, Object> data = flowTaskUtil.infoData(taskNode.getFormId(), taskNode.getTaskId());
                    messageModel.setData(data);
                    messageModel.setTitle("有关于您的评论，请及时查看");

                    messageModel.setMsgConfig(commentMsgConfig);
                    messageModel.setRecordEntity(recordEntity);
                    messageModel.setStatus(taskEntity.getStatus());
                    messageModel.setFullName(messageModel.getTitle());
                    messageModel.setUserInfo(userInfo);
                    messageModel.setType(3);

                    messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                    setMessageList(messageList, messageModel);
                    messageListAll.addAll(messageList);
                    for (FlowTaskOperatorEntity operator : taskOperatorList) {
                        List<SentMessageForm> delegationMsg = delegationMsg(operator, messageModel, flowTemplateAllModel);
                        messageListAll.addAll(delegationMsg);
                    }
                }
            }
            //抄送人
            if (circulateList != null && !circulateList.isEmpty()) {
                Map<String, List<FlowTaskCirculateEntity>> circulateMap = circulateList.stream().collect(Collectors.groupingBy(FlowTaskCirculateEntity::getTaskNodeId));
                for (String key : circulateMap.keySet()) {
                    recordEntity.setTaskNodeId(key);
                    //默认获取当前节点
                    FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(key)).findFirst().orElse(null);
                    List<SentMessageForm> messageList = new ArrayList<>();
                    List<FlowTaskOperatorEntity> taskOperatorList = new ArrayList<>();
                    for (FlowTaskCirculateEntity circulateEntity : circulateMap.get(key)) {
                        FlowTaskOperatorEntity operatorEntity = JsonUtil.getJsonToBean(circulateEntity, FlowTaskOperatorEntity.class);
                        operatorEntity.setHandleId(circulateEntity.getObjectId());
                        taskOperatorList.add(operatorEntity);
                    }
                    FlowMessageModel messageModel = new FlowMessageModel();
                    Map<String, Object> data = flowTaskUtil.infoData(taskNode.getFormId(), taskNode.getTaskId());
                    messageModel.setData(data);
                    messageModel.setTitle("有关于您的评论，请及时查看");
                    messageModel.setMsgConfig(commentMsgConfig);
                    messageModel.setRecordEntity(recordEntity);
                    messageModel.setStatus(taskEntity.getStatus());
                    messageModel.setType(FlowMessageEnum.circulate.getCode());
                    messageModel.setFullName(messageModel.getTitle());
                    messageModel.setUserInfo(userInfo);
                    messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                    setMessageList(messageList, messageModel);
                    messageListAll.addAll(messageList);
                }
            }
            //发起人
            if (StringUtil.isNotEmpty(flowMsgModel.getStartHandId())) {
                List<SentMessageForm> messageList = new ArrayList<>();
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowTaskUtil.infoData(properties.getFormId(), childNode.getTaskId());
                messageModel.setData(data);
                messageModel.setTitle("有关于您的评论，请及时查看");
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setMsgConfig(commentMsgConfig);
                messageModel.setType(FlowMessageEnum.me.getCode());
                messageModel.setFullName(messageModel.getTitle());
                messageModel.setUserInfo(userInfo);
                List<FlowTaskOperatorEntity> meOperatorList = new ArrayList() {{
                    FlowTaskOperatorEntity operatorEntity = new FlowTaskOperatorEntity();
                    operatorEntity.setTaskId(taskEntity.getId());
                    operatorEntity.setHandleId(flowMsgModel.getStartHandId());
                    add(operatorEntity);
                }};
                messageModel(meOperatorList, flowTemplateAllModel, messageModel);
                setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
            }

            //审批已办记录
            List<FlowTaskOperatorRecordEntity> operatorRecordList = flowMsgModel.getOperatorRecordList();
            if (operatorRecordList != null && !operatorRecordList.isEmpty()) {
                Map<String, List<FlowTaskOperatorRecordEntity>> operatorRecordMap = operatorRecordList.stream().collect(Collectors.groupingBy(FlowTaskOperatorRecordEntity::getTaskNodeId));
                for (String key : operatorRecordMap.keySet()) {
                    recordEntity.setTaskNodeId(key);
                    List<SentMessageForm> messageList = new ArrayList<>();
                    List<FlowTaskOperatorRecordEntity> taskOperatorList = operatorRecordMap.get(key);
                    FlowMessageModel messageModel = new FlowMessageModel();
                    FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(recordEntity.getTaskNodeId())).findFirst().orElse(null);
                    Map<String, Object> data = flowTaskUtil.infoData(taskNode.getFormId(), taskNode.getTaskId());
                    messageModel.setData(data);
                    messageModel.setTitle("有关于您的评论，请及时查看");

                    messageModel.setMsgConfig(commentMsgConfig);
                    messageModel.setRecordEntity(recordEntity);
                    messageModel.setStatus(taskEntity.getStatus());
                    messageModel.setFullName(messageModel.getTitle());
                    messageModel.setUserInfo(userInfo);
                    messageModel.setType(3);

                    messageModelRecord(taskOperatorList, flowTemplateAllModel, messageModel);
                    setMessageList(messageList, messageModel);
                    messageListAll.addAll(messageList);
                }
            }*/
        }


        if (flowMsgModel.getMessageFlag()) {
            MsgConfig messageMsgConfig = currentNodeProperties.getMessageMsgConfig();
            Map<String, List<FlowTaskCirculateEntity>> circulateMap = circulateList.stream().collect(Collectors.groupingBy(FlowTaskCirculateEntity::getTaskNodeId));
            for (String key : circulateMap.keySet()) {
                recordEntity.setTaskNodeId(key);
                //默认获取当前节点
//                FlowTaskNodeEntity taskNode = nodeList.stream().filter(t -> t.getId().equals(key)).findFirst().orElse(null);
//                ChildNodeList taskChildNode = JsonUtil.getJsonToBean(taskNode.getNodePropertyJson(), ChildNodeList.class);
//                Properties taskProperties = taskChildNode.getProperties();
//                MsgConfig taskMsgConfig = taskProperties.getCopyMsgConfig();
//                if (taskMsgConfig.getOn() == 2) {
//                    taskMsgConfig = msgConfig;
//                }
//                if (taskMsgConfig.getOn() == 3) {
//                    taskMsgConfig.setMsgId("PZXTLC007");
//                }
                List<SentMessageForm> messageList = new ArrayList<>();
                List<FlowTaskOperatorEntity> taskOperatorList = new ArrayList<>();
                for (FlowTaskCirculateEntity circulateEntity : circulateMap.get(key)) {
                    FlowTaskOperatorEntity operatorEntity = JsonUtil.getJsonToBean(circulateEntity, FlowTaskOperatorEntity.class);
                    operatorEntity.setHandleId(circulateEntity.getObjectId());
                    taskOperatorList.add(operatorEntity);
                }
                FlowMessageModel messageModel = new FlowMessageModel();
                Map<String, Object> data = flowMsgModel.getData();
                messageModel.setData(data);
                messageModel.setTitle("已被【通知】");
                messageModel.setMsgConfig(messageMsgConfig);
                messageModel.setRecordEntity(recordEntity);
                messageModel.setStatus(taskEntity.getStatus());
                messageModel.setType(FlowMessageEnum.circulate.getCode());
                messageModel.setFullName(taskEntity.getFullName());
                messageModel.setUserInfo(userInfo);
                this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
                this.setMessageList(messageList, messageModel);
                messageListAll.addAll(messageList);
            }
        }

        for (SentMessageForm sentMessageForm : messageListAll) {
            FlowTemplateJsonEntity templateJson = flowTemplateAllModel.getTemplateJson();
            sentMessageForm.setFlowName(templateJson.getFullName());
            sentMessageForm.setUserName(user != null ? user.getRealName() : "");
        }


        serviceUtil.sendMessage(messageListAll);
    }

    /**
     * 封装站内信消息
     */
    private void messageModel(List<FlowTaskOperatorEntity> taskOperatorList, FlowTemplateAllModel flowTemplateAllModel, FlowMessageModel messageModel) {
        List<String> userList = new ArrayList<>();
        Map<String, String> contMsg = new HashMap<>();
        for (FlowTaskOperatorEntity taskOperator : taskOperatorList) {
            FlowContModel contModel = this.flowMessage(flowTemplateAllModel, taskOperator, messageModel);
            contMsg.put(taskOperator.getHandleId(), JsonUtil.getObjectToString(contModel));
            userList.add(taskOperator.getHandleId());
        }
        messageModel.setUserList(userList);
        messageModel.setContMsg(contMsg);
    }

    /**
     * 封装站内信对象
     *
     * @param taskOperator
     * @return
     */
    private FlowContModel flowMessage(FlowTemplateAllModel flowTemplateAllModel, FlowTaskOperatorEntity taskOperator, FlowMessageModel messageModel) {
        FlowTemplateJsonEntity templateJson = flowTemplateAllModel.getTemplateJson();
        FlowTemplateEntity template = flowTemplateAllModel.getTemplate();
        FlowContModel contModel = new FlowContModel();
        contModel.setEnCode(template.getEnCode());
        contModel.setFlowId(templateJson.getId());
        contModel.setTaskNodeId(taskOperator.getTaskNodeId());
//        contModel.setTaskOperatorId(taskOperator.getId());
        contModel.setTaskOperatorId(taskOperator.getTaskNodeId());
        contModel.setProcessId(taskOperator.getTaskId());
        contModel.setType(messageModel.getType());
        contModel.setStatus(messageModel.getStatus());
        return contModel;
    }

    /**
     * 整合发送消息
     *
     * @param messageList
     * @param flowMessageModel
     */
    private void setMessageList(List<SentMessageForm> messageList, FlowMessageModel flowMessageModel) {
        Map<String, Object> data = new HashMap<>(flowMessageModel.getData());
        MsgConfig msgConfig = flowMessageModel.getMsgConfig() != null ? flowMessageModel.getMsgConfig() : new MsgConfig();
        List<String> userList = flowMessageModel.getUserList();
        FlowTaskOperatorRecordEntity record = flowMessageModel.getRecordEntity();
        String templateId = msgConfig.getOn() == 0 ? "0" : msgConfig.getMsgId();
        Boolean sysMessage = msgConfig.getOn() != 0;
        //解析发送配置json，获取消息模板参数
        List<TemplateJsonModel> templateJson = new ArrayList<>();
        for (SendConfigJson sendConfigJson : msgConfig.getTemplateJson()) {
            List<TemplateJsonModel> templateJson1 = sendConfigJson.getParamJson();
            templateJson.addAll(templateJson1);
            List<String> paramJson = ImmutableList.of(FlowConstant.MANDATOR, FlowConstant.MANDATARY, FlowConstant.CREATORUSERNAME, FlowConstant.SENDTIME);
            for (String field : paramJson) {
                TemplateJsonModel templateJsonModel = new TemplateJsonModel();
                templateJsonModel.setMsgTemplateId(sendConfigJson.getId());
                templateJsonModel.setRelationField(field);
                templateJsonModel.setField(field);
                templateJsonModel.setSourceType(TemplateEnum.System.getCode());
                templateJson.add(templateJsonModel);
            }
        }
        SentMessageForm messageModel = new SentMessageForm();
        messageModel.setSysMessage(sysMessage);
        messageModel.setTemplateId(templateId);
        messageModel.setToUserIds(userList);
        Map<String, Object> parameterMap = new HashMap<>();
        for (TemplateJsonModel templateJsonModel : templateJson) {
            String fieldId = templateJsonModel.getField();
            String msgTemplateId = templateJsonModel.getMsgTemplateId();
            String relationField = templateJsonModel.getRelationField();
            String dataValue = data.get(relationField) != null ? String.valueOf(data.get(relationField)) : "";
            String dataFieldValue = relationField;
            String dataJson = Objects.equals(TemplateEnum.Field.getCode(),templateJsonModel.getSourceType()) ? dataValue : dataFieldValue;
            FlowEventModel eventModel = FlowEventModel.builder().data(data).dataJson(dataJson).recordEntity(record).templateJson(templateJsonModel).build();
            dataJson = this.dataMsg(eventModel);
            parameterMap.put(msgTemplateId + fieldId, dataJson);
        }
        data.putAll(parameterMap);
        messageModel.setUserInfo(flowMessageModel.getUserInfo());
        messageModel.setParameterMap(data);
        messageModel.setContentMsg(flowMessageModel.getContMsg());
        messageModel.setTitle(flowMessageModel.getFullName());
        if (userList.size() > 0) {
            messageList.add(messageModel);
        }
    }

    /**
     * @return
     */
    private String dataEvent(FlowEventModel eventModel) {
        FlowTaskOperatorRecordDTO record = eventModel.getRecord();
        TemplateJsonModel templateJson = eventModel.getTemplateJson();
        String relationField = StringUtil.isNotEmpty(templateJson.getRelationField()) ? templateJson.getRelationField() : "";
        List<Integer> typeList = ImmutableList.of(TemplateEnum.Field.getCode(), TemplateEnum.System.getCode());
        boolean isType = typeList.contains(templateJson.getSourceType());
        boolean isSubTable = templateJson.getIsSubTable();
        String dataJson = eventModel.getDataJson();
        Map<String, Object> data = eventModel.getData();
        UserInfo userInfo = userProvider.get();
        String userId = StringUtil.isNotEmpty(userInfo.getUserId()) ? userInfo.getUserId() : StringUtil.isNotEmpty(record.getAssignee()) ? record.getAssignee() : "";
        UserEntity userEntity = serviceUtil.getUserInfo(userId);
        String userName = userEntity != null ? userEntity.getRealName() : "";
        String value = dataJson;
//        FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(record.getTaskId(), FlowTaskEntity::getFlowId
//                , FlowTaskEntity::getFlowName, FlowTaskEntity::getFullName, FlowTaskEntity::getCreatorUserId);
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(record.getProcessInstanceId()).includeProcessVariables().singleResult();
        Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
        if (isType) {
            switch (relationField) {
                case "@flowId":
                    LambdaQueryWrapper<FlowTemplateJsonEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(FlowTemplateJsonEntity::getProcessDefinitionId,historicProcessInstance.getProcessDefinitionId());
                    lambdaQueryWrapper.select(FlowTemplateJsonEntity::getId);
                    FlowTemplateJsonEntity flowTemplateJsonEntity = flowTemplateJsonService.getOne(lambdaQueryWrapper);
                    value = flowTemplateJsonEntity.getId();
                    break;
                case "@taskId":
                    value = record.getProcessInstanceId();
                    break;
                case "@taskNodeId":
                    value = record.getTaskId();
                    break;
                case "@flowFullName":
                    value = historicProcessInstance.getProcessDefinitionName();
                    break;
                case "@taskFullName":
                    value = MapUtil.getStr(processVariables,BUSINESS_TITLE);
                    break;
                case "@launchUserId":
                    value = historicProcessInstance.getStartUserId();
                    break;
                case "@launchUserName":
                    UserEntity createUser = historicProcessInstance != null ? serviceUtil.getUserInfo(historicProcessInstance.getStartUserId()) : null;
                    value = createUser != null ? createUser.getRealName() : "";
                    break;
                case "@flowOperatorUserId":
                    value = userId;
                    break;
                case "@flowOperatorUserName":
                    value = userName;
                    break;
                case "@businessMainKey":
                    value = MapUtil.getStr(processVariables,BUSINESS_KEY);
                    break;
                case "@isStartNode":
                    value = (String) data.get(relationField);
                    break;
                case "@formData":
                    value = JSONUtil.toJsonStr(data).replaceAll("\\\"", "\\\\\"");
                    break;
                default:
                    String[] model = StringUtil.isNotEmpty(relationField) ? relationField.split("-") : new String[]{};
                    if (model.length > 1) {
                        Object dataList = data.get(model[0]);
                        if (dataList instanceof List) {
                            List<Map<String, Object>> listAll = (List<Map<String, Object>>) dataList;
                            List<Object> list = new ArrayList<>();
                            for (Map<String, Object> objectMap : listAll) {
                                list.add(objectMap.get(model[1]));
                            }
                            value = String.valueOf(list);
                        }
                    }
                    break;
            }
        }
        return value;
    }
    private String dataStartEvent(FlowEventModel eventModel) {
        FlowTaskOperatorRecordDTO record = eventModel.getRecord();
        TemplateJsonModel templateJson = eventModel.getTemplateJson();
        String relationField = StringUtil.isNotEmpty(templateJson.getRelationField()) ? templateJson.getRelationField() : "";
        List<Integer> typeList = ImmutableList.of(TemplateEnum.Field.getCode(), TemplateEnum.System.getCode());
        boolean isType = typeList.contains(templateJson.getSourceType());
        boolean isSubTable = templateJson.getIsSubTable();
        String dataJson = eventModel.getDataJson();
        Map<String, Object> data = eventModel.getData();
        log.info("dataJson:{}",dataJson);
        log.info("data:{}",data);
        UserInfo userInfo = userProvider.get();
        String userId = StringUtil.isNotEmpty(userInfo.getUserId()) ? userInfo.getUserId() : StringUtil.isNotEmpty(record.getAssignee()) ? record.getAssignee() : "";
        UserEntity userEntity = serviceUtil.getUserInfo(userId);
        String userName = userEntity != null ? userEntity.getRealName() : "";
        String value = dataJson;
//        FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(record.getTaskId(), FlowTaskEntity::getFlowId
//                , FlowTaskEntity::getFlowName, FlowTaskEntity::getFullName, FlowTaskEntity::getCreatorUserId);
//        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(record.getTaskId()).includeProcessVariables().singleResult();
//        Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
        if (isType) {
            switch (relationField) {
                case "@flowId":
                    LambdaQueryWrapper<FlowTemplateJsonEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(FlowTemplateJsonEntity::getProcessDefinitionId,MapUtil.getStr(data,"processDefinitionId"));
                    lambdaQueryWrapper.select(FlowTemplateJsonEntity::getId);
                    FlowTemplateJsonEntity flowTemplateJsonEntity = flowTemplateJsonService.getOne(lambdaQueryWrapper);
                    value = flowTemplateJsonEntity.getId();
                    break;
                case "@taskId":
                    value = record.getProcessInstanceId();
                    break;
                case "@taskNodeId":
                    value = record.getTaskId();
                    break;
                case "@flowFullName":
                    value =MapUtil.getStr(data,"processDefinitionName");
                    break;
                case "@taskFullName":
                    value = MapUtil.getStr(data,BUSINESS_TITLE);
                    break;
                case "@launchUserId":
                    value = MapUtil.getStr(data,APPLY_USER_ID);
                    break;
                case "@launchUserName":
                    UserEntity createUser = serviceUtil.getUserInfo(MapUtil.getStr(data,APPLY_USER_ID)) ;
                    value = createUser != null ? createUser.getRealName() : "";
                    break;
                case "@flowOperatorUserId":
                    value = userId;
                    break;
                case "@flowOperatorUserName":
                    value = userName;
                    break;
                case "@businessMainKey":
                    value = MapUtil.getStr(data,BUSINESS_KEY);
                    break;
                case "@isStartNode":
                    value = (String) data.get(relationField);
                    break;
                case "@formData":
                    value = JSONUtil.toJsonStr(data).replaceAll("\\\"", "\\\\\"");
                    break;
                default:
                    String[] model = StringUtil.isNotEmpty(relationField) ? relationField.split("-") : new String[]{};
                    if (model.length > 1) {
                        Object dataList = data.get(model[0]);
                        if (dataList instanceof List) {
                            List<Map<String, Object>> listAll = (List<Map<String, Object>>) dataList;
                            List<Object> list = new ArrayList<>();
                            for (Map<String, Object> objectMap : listAll) {
                                list.add(objectMap.get(model[1]));
                            }
                            value = String.valueOf(list);
                        }
                    }
                    break;
            }
        }
        return value;
    }

    private Map<String, Object> parseMapUnder(Map<String, Object> sourceMap) {
        Map<String, Object> resultMap = new HashMap<>();
        for (Map.Entry<String, Object> entry : sourceMap.entrySet()) {
            resultMap.put(entry.getKey().replaceAll("@", ""), entry.getValue());
        }
        return resultMap;
    }

    private String dataMsg(FlowEventModel eventModel) {
        FlowTaskOperatorRecordEntity record = eventModel.getRecordEntity();
        TemplateJsonModel templateJson = eventModel.getTemplateJson();
        String relationField = StringUtil.isNotEmpty(templateJson.getRelationField()) ? templateJson.getRelationField() : "";
        boolean isType = "1".equals(templateJson.getSourceType());
        boolean isSubTable = templateJson.getIsSubTable();
        String dataJson = eventModel.getDataJson();
        Map<String, Object> data = eventModel.getData();
        UserInfo userInfo = userProvider.get();
        String userId = StringUtil.isNotEmpty(userInfo.getUserId()) ? userInfo.getUserId() : StringUtil.isNotEmpty(record.getHandleId()) ? record.getHandleId() : "";
        UserEntity userEntity = serviceUtil.getUserInfo(userId);
        String userName = userEntity != null ? userEntity.getRealName() : "";
        String value = dataJson;
//        FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(record.getTaskId(), FlowTaskEntity::getFlowId
//                , FlowTaskEntity::getFlowName, FlowTaskEntity::getFullName, FlowTaskEntity::getCreatorUserId);
        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(record.getTaskId()).includeProcessVariables().singleResult();
        Map<String, Object> processVariables = historicProcessInstance.getProcessVariables();
        if (isType) {
            switch (relationField) {
                case "@flowId":
                    LambdaQueryWrapper<FlowTemplateJsonEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper.eq(FlowTemplateJsonEntity::getProcessDefinitionId,historicProcessInstance.getProcessDefinitionId());
                    lambdaQueryWrapper.select(FlowTemplateJsonEntity::getId);
                    FlowTemplateJsonEntity flowTemplateJsonEntity = flowTemplateJsonService.getOne(lambdaQueryWrapper);
                    value = flowTemplateJsonEntity.getId();
                    break;
                case "@taskId":
                    value = record.getTaskId();
                    break;
                case "@taskNodeId":
                    value = record.getTaskNodeId();
                    break;
                case "@flowFullName":
                    value = historicProcessInstance.getProcessDefinitionName();
                    break;
                case "@taskFullName":
                    value = MapUtil.getStr(processVariables,BUSINESS_TITLE);
                    break;
                case "@launchUserId":
                    value = historicProcessInstance.getStartUserId();
                    break;
                case "@launchUserName":
                    UserEntity createUser = historicProcessInstance != null ? serviceUtil.getUserInfo(historicProcessInstance.getStartUserId()) : null;
                    value = createUser != null ? createUser.getRealName() : "";
                    break;
                case "@flowOperatorUserId":
                    value = userId;
                    break;
                case "@flowOperatorUserName":
                    value = userName;
                    break;
                case "@businessMainKey":
                    value = MapUtil.getStr(processVariables,BUSINESS_KEY);
                    break;
                default:
                    String[] model = StringUtil.isNotEmpty(relationField) ? relationField.split("-") : new String[]{};
                    if (model.length > 1) {
                        Object dataList = data.get(model[0]);
                        if (dataList instanceof List) {
                            List<Map<String, Object>> listAll = (List<Map<String, Object>>) dataList;
                            List<Object> list = new ArrayList<>();
                            for (Map<String, Object> objectMap : listAll) {
                                list.add(objectMap.get(model[1]));
                            }
                            value = String.valueOf(list);
                        }
                    }
                    break;
            }
        }
        return value;
    }


    //--------------------------------------------事件处理---------------------------------------------------------

    /**
     * 流程事件
     *
     * @param status    事件状态 1.发起 2.结束 3.发起撤回 4同意 5拒绝 6节点撤回 7 超时 8提醒
     *                     作用是用来判断是什么事件
     * @param properties 节点数据
     * @param record    审批数据
     */
    public ActionResult event(Integer status, Properties properties, FlowTaskOperatorRecordDTO record, FlowModel flowModel, Process bpmnModelMainProcess,String taskDefinitionKey) {
        boolean on = false;
            String interId = "";
            List<TemplateJsonModel> templateJsonModelList = new ArrayList<>();
            FuncConfig config = null;
            List<Integer> eventList = ImmutableList.of(2, 7, 8);
            Map<Integer,String> map = new HashMap();
            map.put(1, "发起事件");
            map.put( 2, "结束事件");
            map.put(3, "撤回事件");
            map.put( 4, "同意事件");
            map.put(5, "退回事件");
            map.put(6, "撤回事件");
            map.put(7, "超时事件");
            map.put(8, "提醒事件");
            map.put(9,"终止事件");
            map.put(10,"HTTP事件");
            map.put(11,"SQL事件");
            map.put(12,"条件事件");
            map.put(13,"审批找人事件");
            //属性
            Integer funcConfigRule = properties.getFuncConfigRule();
            switch (status) {
                case 1:
                    config = properties.getInitFuncConfig();
                    break;
                case 2:
                    config = properties.getEndFuncConfig();
                    break;
                case 3:
                    config = properties.getFlowRecallFuncConfig();
                    break;
                case 4:
                    config = properties.getApproveFuncConfig();
                    break;
                case 5:
                    config = properties.getRejectFuncConfig();
                    break;
                case 6:
                    config = properties.getRecallFuncConfig();
                    break;
                case 7:
                    config = properties.getOvertimeFuncConfig();
                    break;
                case 8:
                    config = properties.getNoticeFuncConfig();
                    break;
                case 9:
                    config = properties.getCancelFuncConfig();
                    break;
                case 10:
                    config = properties.getHttpInitFuncConfig();
                    break;
                case 11:
                    config = properties.getSqlInitFuncConfig();
                    break;
                case 12:
                    config = properties.getConditionFuncConfig();
                    break;
                case 13:
                    config = properties.getInterfaceConfig();
                    break;
                default:
                    break;
            }
            //基础事件处理
            config = baseFuncProcess(bpmnModelMainProcess,status,config);
            //填充系统变量
            metaFlowSystemVariable(flowModel,bpmnModelMainProcess,taskDefinitionKey);
            if (config != null) {
                on = config.getOn();
                interId = config.getInterfaceId();
                //获取事件表单字段列表
                templateJsonModelList = config.getTemplateJson();
            }
            if (on && StringUtil.isNotEmpty(interId)) {
                Map<String, Object> data = flowModel.getFormData();
                //表单字段值映射
                Map<String, String> parameterMap = parameterMaps(status, record, templateJsonModelList, data);
                log.info("parameterMap:{}", JSONObject.toJSONString(parameterMap));
                parameterMap.put("handleOpinion",flowModel.getHandleOpinion());
                ActionResult result = serviceUtil.infoToId(interId, parameterMap);
                    boolean error = Objects.equals(400, result.getCode());
                    FlowEventLogEntity logEntity = new FlowEventLogEntity();
                    logEntity.setTaskNodeId(record.getTaskId());
                    logEntity.setFullName(map.get(status));
                    logEntity.setInterfaceId(interId);
                    logEntity.setResult(error ? result.getMsg() : "执行成功");
                InterfaceInfoModel interfaceModel = FlowContextHolder.getInterfaceModel();
                if(interfaceModel!=null){
                    String inputStr = interfaceModel.getInput();
                    String outPutStr = interfaceModel.getOutput();
                    logEntity.setInputStr(inputStr);
                    logEntity.setOutPutStr(outPutStr);
                }
                logEntity.setRespStatus(error ? "2":"3");
                flowEventLogService.create(logEntity);
                    return result;
            }
            return ActionResult.success();
    }

    private FuncConfig baseFuncProcess(Process process,Integer status,FuncConfig config){
        if (!ObjectUtil.isNull(config) && config.getOn()){
            return config;
        }
        if (ObjectUtil.isNull(process)){
            return config;
        }
        //获取第一个节点的基础配置
        FuncBaseConfig baseFuncConfig = BpmnModelUtils.getElementProperty(process).getBaseFuncConfig();
        if (ObjectUtil.isNull(baseFuncConfig)){
            return config;
        }
        //通过状态获取事件code
        FlowEventEnum flowEventEnumByStatus = FlowEventEnum.getFlowEventEnumByStatus(status);
        if (ObjectUtil.isNull(flowEventEnumByStatus)){
            return config;
        }
        //判断基础事件是否配置该事件code
        if (CollectionUtil.isEmpty(baseFuncConfig.getEventCodes()) || !baseFuncConfig.getEventCodes().contains(flowEventEnumByStatus.getCode())) {
            return config;
        }
        //判断基础事件是否开启
        if (!baseFuncConfig.getOn()){
            return config;
        }
        return baseFuncConfig;
    }

    /**
     * 设置流程系统变量参数
     * @param flowModel
     * @param bpmnModelMainProcess
     * @param task
     */
    private void metaFlowSystemVariable(FlowModel flowModel, Process bpmnModelMainProcess, String taskDefinitionKey) {
        //是否是开始节点
        flowModel.getFormData().put("@isStartNode", getIsStartEvent(bpmnModelMainProcess, taskDefinitionKey)?"1":"0");
    }

    @NotNull
    private Map<String, String> parameterMaps(Integer status, FlowTaskOperatorRecordDTO record, List<TemplateJsonModel> templateJsonModelList, Map<String, Object> data) {
        Map<String, String> parameterMap = new HashMap<>();
        log.info("data-------------->{}",JSONObject.toJSONString(data));
        for (TemplateJsonModel templateJsonModel : templateJsonModelList) {
            String fieldId = templateJsonModel.getField();
            String relationField = templateJsonModel.getRelationField();
            String dataValue = data.get(relationField) != null ? String.valueOf(data.get(relationField)) : null;
            log.info("-------------->relationField:{},dataValue:{}",relationField,dataValue);
            String dataFieldValue = relationField;
            String dataJson = TemplateEnum.Field.getCode().equals(templateJsonModel.getSourceType()) ? dataValue : dataFieldValue;
            FlowEventModel eventModel = FlowEventModel.builder().data(data).dataJson(dataJson).record(record).templateJson(templateJsonModel).build();
            if(status ==1){
                //
                dataJson = this.dataStartEvent(eventModel);
                parameterMap.put(fieldId, dataJson);
            }
            else{

                dataJson = this.dataEvent(eventModel);
                parameterMap.put(fieldId, dataJson);
            }
        }
        return parameterMap;
    }


    /**
     * 封装委托消息
     *
     * @param operator
     * @param messageModel
     * @return
     */
    private List<SentMessageForm> delegationMsg(FlowTaskOperatorEntity operator, FlowMessageModel messageModel, FlowTemplateAllModel flowTemplateAllModel) {
        List<SentMessageForm> messageList = new ArrayList<>();
//        FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(operator.getTaskId(), FlowTaskEntity::getFlowId);
//        if (taskEntity != null) {
//            //todo 获取委托人
//            List<String> userList = flowDelegateService.getUser(null, taskEntity.getTemplateId(), operator.getHandleId()).stream().map(FlowDelegateEntity::getToUserId).collect(Collectors.toList());
//            List<FlowTaskOperatorEntity> taskOperatorList = new ArrayList<>();
//            for (String user : userList) {
//                FlowTaskOperatorEntity delegaOperator = JsonUtil.getJsonToBean(operator, FlowTaskOperatorEntity.class);
//                delegaOperator.setHandleId(user);
//                taskOperatorList.add(delegaOperator);
//            }
//            this.messageModel(taskOperatorList, flowTemplateAllModel, messageModel);
//            this.setMessageList(messageList, messageModel);
//        }
        return messageList;
    }


    //--------------------------------------委托消息------------------------------------------------------
    public void delegateMsg(FlowDelegateModel flowDelegate) {
        List<String> toUserIds = flowDelegate.getToUserIds();
        UserInfo userInfo = flowDelegate.getUserInfo();
        FlowTaskEntity flowTask = flowDelegate.getFlowTask();
        FlowTemplateAllModel templateAllModel = flowDelegate.getTemplateAllModel();
        Map<String, String> contentMsg = new HashMap<>();
        Boolean delegate = flowDelegate.getDelegate();
        boolean approve = flowDelegate.getApprove();
        if (approve) {
            SentMessageForm flowMsgModel = new SentMessageForm();
            flowMsgModel.setToUserIds(toUserIds);
            flowMsgModel.setUserInfo(flowDelegate.getUserInfo());
//            String flowName  = flowTask.getFlowName();
            String flowName = templateAllModel.getTemplateJson().getFullName();
            Map<String, Object> parameterMap = new HashMap<>();
            parameterMap.put("@Mandator", userInfo.getUserName());
            parameterMap.put("@Title", flowTask != null ? flowTask.getFullName() : "");
            flowMsgModel.setParameterMap(parameterMap);
            //1.委托设置 2.委托给我
            Integer type = flowDelegate.getType();
            if (delegate) {
                String title = FlowNature.StartMsg.equals(type) ? "了发起委托" : FlowNature.ApproveMsg.equals(type) ? "了审批委托" : "的委托已结束";
                String templateId = FlowNature.StartMsg.equals(type) ? "PZXTLG012" : FlowNature.ApproveMsg.equals(type) ? "PZXTLG013" : "PZXTLG014";
                String content = userInfo.getUserName() + "向您发起" + title;
                flowMsgModel.setTitle(content);
                flowMsgModel.setTemplateId(templateId);
            } else {
                String title = FlowNature.StartMsg.equals(type) ? "已发起了您的" : "已审批了您的";
                String templateId = FlowNature.StartMsg.equals(type) ? "PZXTLG015" : "PZXTLG016";
                String content = userInfo.getUserName() + title + flowName;
                flowMsgModel.setTitle(content);
                flowMsgModel.setTemplateId(templateId);
            }
            Integer delegateType = delegate ? FlowNature.EndMsg : FlowNature.ApproveMsg;
            contentMsg.put("type", delegateType + "");
            flowMsgModel.setContentMsg(contentMsg);
            flowMsgModel.setFlowType(2);
            flowMsgModel.setType(2);
            List<SentMessageForm> messageListAll = new ArrayList<>();
            if (toUserIds.size() > 0) {
                messageListAll.add(flowMsgModel);
            }
            serviceUtil.sendDelegateMsg(messageListAll);
        }
    }





}
